<template>
    <div>
        <div>
            <el-divider content-position="left">您具有一定的操作权限</el-divider>
        </div>

        <el-divider>
            <span id="spanlittlepart">查询</span>
        </el-divider>

        <!-- 查询 -->
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="标题" style="width: 150px;">
                <el-input v-model="checkformInline.title" placeholder="title"></el-input>
            </el-form-item>
            <el-form-item label="内容" style="width: 150px;">
                <el-input v-model="checkformInline.content" placeholder="content"></el-input>
            </el-form-item>
            <el-form-item style="width: 200px;">
                <el-button @click="search" type="primary" plain style="width: 200px;">查询</el-button>
            </el-form-item>
        </el-form>

        <el-divider>
            <el-icon><star-filled /></el-icon>
        </el-divider>

        <el-button type="primary" plain :onclick="toAddTipsOfficial" class="addbtn">
            <el-icon>
                <Edit />
            </el-icon>
            <span>创建新的官方帖子</span>
        </el-button>

        <!-- 展示表格 -->
        <el-table :data="tableData" style="width: 100%" :highlight-current-row="true">
            <el-table-column prop="classification" label="分类" width="80" :filters="[
                    { text: '暂未分类', value: '暂未分类' },
                    { text: '新手必看', value: '新手必看' },
                    { text: '防止病虫害', value: '防止病虫害' },
                    { text: '修枝剪叶', value: '修枝剪叶' },
                    { text: '植物养护', value: '植物养护' },
                ]" :filter-method="filterHandler" />
            <el-table-column prop="date" :formatter="Formatter" label="添加时间" width="" />
            <el-table-column prop="isrotograph" label="是否为轮播图" width="125px" :filters="[
                    { text: '是轮播图', value: '是轮播图' },
                    { text: '非轮播图', value: '非轮播图' },
                ]" :filter-method="filterHandler" />
            <el-table-column prop="title" label="标题" width="100" />
            <el-table-column prop="content" label="内容" width="280" show-overflow-tooltip />
            <el-table-column label="轮播图封面" width="200">
                <template #default="scope">
                    <div style="display: flex; align-items: center">
                        <el-image :fit="contain"
                            style="width: 190px;height: 80px;  padding-left: -30px;margin-left: -30px; overflow: visible;"
                            :src="this.baseURL + tableData[scope.$index].coverimgbig"
                            :preview-src-list="[this.baseURL + tableData[scope.$index].coverimgbig]" :preview-teleported="true"
                            :initial-index="scope.$index" />
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="列表封面" width="90">
                <template #default="scope">
                    <div style="display: flex; align-items: center">
                        <el-image :fit="contain"
                            style=" width: 80px;height: 80px; padding-left: -30px;margin-left: -30px; overflow: visible;"
                            :src="this.baseURL + tableData[scope.$index].coverimgsmall"
                            :preview-src-list="this.baseURL + tableData[scope.$index].coverimgsmall" :preview-teleported="true"
                            :initial-index="scope.$index" />
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="内容插图" width="200">
                <template #default="scope">
                    <div style="display: flex; align-items: center">
                        <el-image :fit="contain"
                            style="width: 190px;height: 80px; padding-left: -30px;margin-left: -30px; overflow: visible;"
                            :src="this.baseURL + tableData[scope.$index].innerimg" :preview-src-list="this.baseURL + tableData[scope.$index].innerimg"
                            :preview-teleported="true" :initial-index="scope.$index" />
                    </div>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="110">
                <template #default="scope">
                    <el-button link type="primary" size="small" style="margin-left: 0;"
                        @click.prevent="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button link type="primary" size="small" style="margin-left: 0;"
                        @click.prevent="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination background layout="prev, pager, next" :current-page="page" @update:current-page="handleCurrentChange"
            :total="total" :page-size="size" style="bottom: 0; text-align: center;margin-left: 45%;margin-top: 5px;" />

        <!-- Form -->
        <el-dialog v-model="dialogFormVisible" title="编辑">
            <el-form :model="form">
                <el-form-item label="分类" :label-width="formLabelWidth">
                    <el-select v-model="form.classification" placeholder="请选择新手必看/防止病虫害/修枝剪叶/植物养护/暂未分类">
                        <el-option label="暂未分类" value="暂未分类" />
                        <el-option label="新手必看" value="新手必看" />
                        <el-option label="防止病虫害" value="防止病虫害" />
                        <el-option label="修枝剪叶" value="修枝剪叶" />
                        <el-option label="植物养护" value="植物养护" />
                    </el-select>
                </el-form-item>
                <el-form-item label="是否为轮播图" :label-width="formLabelWidth">
                    <el-select v-model="form.isrotograph" placeholder="请选择是轮播图/非轮播图">
                        <el-option label="是轮播图" value="是轮播图" />
                        <el-option label="非轮播图" value="非轮播图" />
                    </el-select>
                </el-form-item>
                <el-form-item label="标题" :label-width="formLabelWidth">
                    <el-input type="textarea" v-model="form.title" autocomplete="off" />
                </el-form-item>
                <el-form-item label="内容" :label-width="formLabelWidth">
                    <el-input type="textarea" rows="6" v-model="form.content" autocomplete="off" />
                </el-form-item>
            </el-form>
            <div class="contentPics">
                <el-divider content-position="center">-长方形-封面图片</el-divider>
                <el-image class="previewTitlePic" :src="baseURL + form.coverimgbig" :fit="contain" />
            </div>

            <div class="contentPics">
                <el-divider content-position="center">-正方形-封面图片</el-divider>
                <el-image class="previewTitlePic" :src="baseURL + form.coverimgsmall" :fit="contain" />
            </div>

            <div class="contentPics">
                <el-divider content-position="center">内容配图</el-divider>
                <el-image class="previewTitlePic" :src="baseURL + form.innerimg" :fit="contain" />
            </div>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="onSaveInfo">
                        提交
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import {
    Guide,
    PictureFilled,
    User,
    HomeFilled,
    ChatLineSquare,
    Apple,
    Document,
    List,
    Tools,
    ShoppingCart,
    CollectionTag,
    Finished,
    InfoFilled,
    Cherry,
    Goods,
    Sell,
    ShoppingCartFull,
    Van,
    Sunrise,
    StarFilled,
    EditPen,
    Edit,
    Promotion,
    Grape,
    Pear,
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs';
import axios from 'axios';
const formLabelWidth = '140px';
const filterHandler = (
    value,
    row,
    column
) => {
    const property = column['property']
    return row[property] === value
}
</script>
<script>

export default {
    setup() {

    },
    data() {
        return {
            baseURL: 'http://localhost:8080',
            rotographChosen: '是轮播图/非轮播图',
            rotographOptions: [
                {
                    value: '是轮播图/非轮播图',
                    label: '是轮播图/非轮播图',
                },
                {
                    value: '是轮播图',
                    label: '是轮播图',
                },
                {
                    value: '非轮播图',
                    label: '非轮播图',
                },
            ],
            classificationChosen: '新手必看/防止病虫害/修枝剪叶/植物养护/暂未分类',
            classificationOptions: [
                {
                    value: '暂未分类',
                    label: '暂未分类',
                },
                {
                    value: '新手必看',
                    label: '新手必看',
                },
                {
                    value: '防止病虫害',
                    label: '防止病虫害',
                },
                {
                    value: '修枝剪叶',
                    label: '修枝剪叶',
                },
                {
                    value: '植物养护',
                    label: '植物养护',
                },
            ],
            formInline: {
                guideid: 0,
                title: '',
                content: '',
                coverimgbig: '',
                innerimg: '',
                coverimgsmall: '',
                isrotograph: 0,
                classification: 0,
                date: 0,
            },
            checkformInline: {
                guideid: 0,
                title: '',
                content: '',
                coverimgbig: '',
                innerimg: '',
                coverimgsmall: '',
                isrotograph: 0,
                classification: 0,
                date: 0,
            },
            dialogFormVisible: false,
            showSearch: false,
            tableData: [],
            tableDataStore: [],
            tablecoverimgbigList: [],
            tablecoverimgbig: '',
            tablecoverimgsmallList: [],
            tablecoverimgsmall: '',
            tableinnerimgList: [],
            tableinnerimg: '',
            tips: {
                guideid: 0,
                title: '',
                content: '',
                coverimgbig: '',
                innerimg: '',
                coverimgsmall: '',
                isrotograph: 0,
                classification: 0,
                date: 0,
            },
            form: {
                guideid: 0,
                title: '',
                content: '',
                coverimgbig: '',
                innerimg: '',
                coverimgsmall: '',
                isrotograph: 0,
                classification: 0,
                date: 0,
            },
            classData: [],
            searchForm: [],
            searchtime: [],
            year: 0,
            month: 0,
            daynum: 0,
            isrotographChange: 0,
            classificationChange: 0,
            page: 1, // 当前页码
            total: 0, // 总条数
            size: 10, // 每页的数据条数
            reallyTable: [],
            selData: [],
        }

    },
    methods: {
        search() {
            let arr = []
            console.log(this.tableDataStore.length)
            for (let i = 0; i < this.tableDataStore.length; i++) {
                if (String(this.tableDataStore[i].title).includes(this.checkformInline.title) &&
                    String(this.tableDataStore[i].content).includes(this.checkformInline.content)) {
                    arr.push(this.tableDataStore[i])
                }
            }
            console.log(arr);
            this.tableData = arr.slice(
                (this.page - 1) * this.size,
                this.page * this.size
            );
            this.selData = arr;
            this.total = arr.length;
        },
        //删除表格行
        handleDelete(index, row) {
            console.log(index, row);
            console.log(row.guideid);//可以获取到
            ElMessageBox.confirm(
                '确认删除本项吗？删除后无法找回:-0',
                'Warning',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
                .then(() => {
                    axios({
                        method: 'post',
                        url: 'http://localhost:8080/tips/deletetipsbackend',
                        withCredentials: true,
                        data: {
                            guideid: row.guideid,
                        },
                    }).then(res => {
                        this.tableData = res.data.data;
                        this.tableDataStore = res.data.data;
                        console.log(res.data.data);
                        this.tableData = res.data.data.slice(
                            (this.page - 1) * this.size,
                            this.page * this.size
                        );
                        this.total = res.data.data.length;
                        this.selData = res.data.data;
                        for (var i = 0; i < res.data.data.length; i++) {
                            this.tablecoverimgbigList.push(res.data.data[i].coverimgbig);
                            this.tablecoverimgsmallList.push(res.data.data[i].coverimgsmall);
                            this.tableinnerimgList.push(res.data.data[i].innerimg);
                            this.getClassification(i);
                            this.getRotograph(i);
                        }
                        //console.log("tableimglist:" + this.tableimgList);
                        this.tablecoverimgbig = this.tablecoverimgbigList[0];
                        this.tablecoverimgsmall = this.tablecoverimgsmallList[0];
                        this.tableinnerimg = this.tableinnerimgList[0];
                        ElMessage({
                            type: 'success',
                            message: '删除成功',
                        })
                    })
                })
                .catch(() => {
                    ElMessage({
                        type: 'info',
                        message: '取消删除操作',
                    })
                })
        },
        //编辑表格行
        handleEdit(index, row) {
            console.log(index, row);
            this.dialogFormVisible = true;
            axios({
                method: 'post',
                url: 'http://localhost:8080/tips/getsingletipsbackend',
                withCredentials: true,
                data: {
                    guideid: index
                },
            }).then(res => {
                this.form = row;
            })
        },
        onSaveInfo() {
            this.form.isrotograph == '非轮播图' ? this.isrotographChange = 0 : this.isrotographChange = 1;
            this.form.classification == '暂未分类' ? this.classificationChange = 0
                : (this.form.classification == '新手必看' ? this.classificationChange = 1
                    : (this.form.classification == '防止病虫害' ? this.classificationChange = 2
                        : (this.form.classification == '修枝剪叶' ? this.classificationChange = 3
                            : this.classificationChange = 4)));

            axios({
                method: 'post',
                url: 'http://localhost:8080/tips/modifytipsbackend',
                withCredentials: true,
                data: {
                    guideid: this.form.guideid,
                    title: this.form.title,
                    content: this.form.content,
                    isrotograph: this.isrotographChange,
                    classification: this.classificationChange,
                    date: new Date().getTime(),
                },
            }).then(res => {
                this.tableData = res.data.data;
                this.tableDataStore = res.data.data;
                console.log(res.data.data);
                this.tableData = res.data.data.slice(
                    (this.page - 1) * this.size,
                    this.page * this.size
                );
                this.total = res.data.data.length;
                this.selData = res.data.data;
                this.classData = res.data.data
                for (var i = 0; i < res.data.data.length; i++) {
                    this.tablecoverimgbigList.push(res.data.data[i].coverimgbig);
                    this.tablecoverimgsmallList.push(res.data.data[i].coverimgsmall);
                    this.tableinnerimgList.push(res.data.data[i].innerimg);
                    this.getClassification(i);
                    this.getRotograph(i);
                }
                //console.log("tableimglist:" + this.tableimgList);
                this.tablecoverimgbig = this.tablecoverimgbigList[0];
                this.tablecoverimgsmall = this.tablecoverimgsmallList[0];
                this.tableinnerimg = this.tableinnerimgList[0];
            })

            this.dialogFormVisible = false;

        },
        handleChangeUploadNew(file, fileList) {
            const isJPG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
                return false
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
                return false
            }
            // 上传成功后将图片地址赋值给data
            this.$nextTick(async () => {
                // base64方式
                // this.cropperOptionBig.img = await fileByBase64(file.raw)
                this.form.coverimgbig = URL.createObjectURL(file.raw)
            })
        },
        handleChangeUploadNewSquare(file, fileList) {
            const isJPG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
                return false
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
                return false
            }
            // 上传成功后将图片地址赋值给data
            this.$nextTick(async () => {
                // base64方式
                // this.cropperOptionBig.img = await fileByBase64(file.raw)
                this.form.coverimgsmall = URL.createObjectURL(file.raw)
            })
        },
        handleChangeUploadNewInner(file, fileList) {
            const isJPG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
                return false
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
                return false
            }
            // 上传成功后将图片地址赋值给data
            this.$nextTick(async () => {
                // base64方式
                // this.cropperOptionBig.img = await fileByBase64(file.raw)
                this.form.innerimg = URL.createObjectURL(file.raw)
            })
        },
        //日期正确表述方法
        formatDate(date) {
            var y = new Date(date).getFullYear();
            var m = new Date(date).getMonth() + 1;
            m = m < 10 ? '0' + m : m;
            var d = new Date(date).getDate();
            d = d < 10 ? ('0' + d) : d;
            return y + '-' + m + '-' + d;
        },
        Formatter(row, column) {
            if (row.create_time) {
                //console.log(new Date(row.create_time));
                this.day = new Date(row.date);
            }
            //console.log(this.formatDate(this.day));
            return this.formatDate(row.date);
        },
        backtosimpleformatDate(date) {
            var y = new Date(date).getFullYear();
            this.year = y;
            var m = new Date(date).getMonth() + 1;
            m = m < 10 ? '0' + m : m;
            this.month = m;
            var d = new Date(date).getDate();
            d = d < 10 ? ('0' + d) : d;
            this.daynum = d;
            return y + '-' + m + '-' + d;
        },
        backtosimpleTime(date) {
            this.searchtime = this.checkformInline.date.split('-');
            this.backtosimpleformatDate(date);
            if (this.searchtime[0] == this.year && this.searchtime[1] == this.month && this.searchtime[2] == this.daynum) {
                return 'get';
            }
            else {
                return 'fail';
            }
        },
        toAddTipsOfficial() {
            console.log('click')
            this.$router.push({
                path: '/addtipsofficial'
            })
        },
        getClassification(index) {
            return (this.selData[index].classification == 0 ? this.selData[index].classification = '暂未分类'
                : (this.selData[index].classification == 1 ? this.selData[index].classification = '新手必看'
                    : (this.selData[index].classification == 2 ? this.selData[index].classification = '防治病虫害'
                        : (this.selData[index].classification == 3 ? this.selData[index].classification = '修枝剪叶' : this.selData[index].classification = '植物养护'))))
        },
        getRotograph(index) {
            return this.selData[index].isrotograph == 0 ? this.selData[index].isrotograph = '非轮播图' : this.selData[index].isrotograph = '是轮播图'
        },
        async handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.page = val
            this.tableData = this.selData.slice(
                (this.page - 1) * this.size,
                this.page * this.size
            );
            // this.currentPage = val;
            const data = { 'page': val }
            // await this.onload(data)
        },
    },
    mounted() {
        //页面加载完成后，将数据库内的内容赋给定义的data变量
        axios({
            method: 'post',
            url: 'http://localhost:8080/tips/gettipsbackend',
            withCredentials: true,
        }).then(res => {
            this.tableData = res.data.data;
            this.tableDataStore = res.data.data;
            console.log(res.data.data);
            this.tableData = res.data.data.slice(
                (this.page - 1) * this.size,
                this.page * this.size
            );
            this.total = res.data.data.length;
            this.selData = res.data.data;
            for (var i = 0; i < res.data.data.length; i++) {
                this.tablecoverimgbigList.push(res.data.data[i].coverimgbig);
                this.tablecoverimgsmallList.push(res.data.data[i].coverimgsmall);
                this.tableinnerimgList.push(res.data.data[i].innerimg);
                this.getClassification(i);
                this.getRotograph(i);
            }
            //console.log("tableimglist:" + this.tableimgList);
            this.tablecoverimgbig = this.tablecoverimgbigList[0];
            this.tablecoverimgsmall = this.tablecoverimgsmallList[0];
            this.tableinnerimg = this.tableinnerimgList[0];
        })
    }
}
</script>
<style scoped>
#sidepart {
    width: 100%;
    position: absolute;
    top: 5px;
    font-family: '华文中宋';
}

#mainpart {
    width: 100%;
    position: absolute;
    top: 20px;
    /* left: 260px; */
    font-family: '华文中宋';
}

#spanpart {
    font-size: 30px;
    font-family: '华文中宋';
}

/* dialog */
.el-button--text {
    margin-right: 15px;
}

.el-select {
    width: 300px;
}

.el-input {
    width: 300px;
}

.dialog-footer button:first-child {
    margin-right: 10px;
}

#spanlittlepart {
    font-size: 15px;
    color: cadetblue;
    font-family: '华文中宋';
}

.bottom {
    width: 300px;
}

.addbtn {
    width: 80%;
    margin-bottom: 20px;
    font-family: '华文中宋';
    position: relative;
    left: -50px;
}

.spaninput {
    width: 950px;
    position: relative;
    top: 0px;
    left: 0px;
    margin-right: 10px;
    margin-top: 10px;
    margin-bottom: 20px;

}

.upload-demo {
    margin-bottom: 10px;
}

.contentPics {
    margin-top: 15px;
    margin-bottom: 15px;
}
</style>